package io.kiki.sba.registry.server.metadata.provide.data;

import io.kiki.sba.registry.common.model.Tuple;
import io.kiki.sba.registry.common.model.console.PersistenceData;
import io.kiki.sba.registry.common.model.console.PersistenceDataBuilder;
import io.kiki.sba.registry.common.model.constants.ValueConstants;
import io.kiki.sba.registry.common.model.metaserver.NodeServerOperateInfo;
import io.kiki.sba.registry.store.api.DBResponse;
import io.kiki.sba.registry.store.api.OperationStatus;
import io.kiki.sba.registry.util.JsonUtils;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;


public class NodeOperatingService {

    @Setter
    @Autowired
    protected ProvideDataService provideDataService;

    protected Tuple<Long, NodeServerOperateInfo> currentVersion = null;

    public NodeOperatingService() {
    }

    public NodeOperatingService(ProvideDataService provideDataService) {
        this.provideDataService = provideDataService;
    }

    public Tuple<Long, NodeServerOperateInfo> queryOperateInfoAndVersion() {
        DBResponse<PersistenceData> response = provideDataService.queryProvideData(ValueConstants.NODE_SERVER_OPERATING_DATA_ID);

        if (response.getOperationStatus() == OperationStatus.notfound) {
            return null;
        }

        String entityData = PersistenceDataBuilder.getEntityData(response.getEntity());

        if (null != currentVersion) {
            if (response.getEntity().getVersion() <= currentVersion.o1) {
                return currentVersion;
            }
        }
        NodeServerOperateInfo read = JsonUtils.gsonRead(entityData, NodeServerOperateInfo.class);
        currentVersion = new Tuple<>(response.getEntity().getVersion(), read);
        return currentVersion;
    }

}
